<template>
  <van-icon
    color="#777"
    :name="isCollected ? 'star' : 'star-o'"
    :class="isCollected ? 'yellow' : ''"
    @click="handelCollect"
  />
</template>

<script>
import { collectArticle, deleteCollect } from '@/api/articles'
export default {
  name: 'CollectItem',
  model: {
    prop: 'isCollected',
    event: 'changeCollect'
  },
  props: {
    isCollected: {
      type: Boolean,
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
    }
  },
  methods: {
    async handelCollect () {
      try {
        if (this.isCollected) { // 被收藏了，点击后取消收藏 颜色变黑
          await deleteCollect(this.articleId)
        } else { // 没被收藏 点击后收藏
          await collectArticle(this.articleId)
        }
        this.$emit('changeCollect', !this.isCollected)
        this.$toast.success(!this.isCollected ? '收藏成功' : '取消收藏')
      } catch (err) {
        this.$toast('操作失败，请稍后重试')
      }
    }
  }
}
</script>

<style>
  .yellow {
    color: #ffa500 !important;
  }
</style>
